<template>
    <el-card class="box-card">
        <el-table border lazy :data="category1List" :load="load" :row-key="getRowKey" :loading="loading"
            style="width:90%; margin-bottom:20px;" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
            <el-table-column label="分类ID" prop="id" align="center" width="150px" />
            <el-table-column label="分类名称" prop="name" />
            <el-table-column align="center" label="操作" width="250">
                <template #header>
                    <el-input placeholder="按Enter键添加一级分类"></el-input>
                </template>
                <template v-slot="{ row }">
                    <el-button title="添加子分类" type="primary" size="small" :icon="Plus"></el-button>
                    <el-button title="修改分类" type="primary" size="small" :icon="Edit"></el-button>
                    <el-button title="删除分类" type="danger" size="small" :icon="Delete"></el-button>
                </template>
            </el-table-column>
        </el-table>
    </el-card>
</template>

<script lang="ts">
export default {
    name: 'Category'
}
</script>
<script lang="ts" setup>
import { Plus, Delete, Edit } from '@element-plus/icons-vue'
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { reqGetCategory1List, reqGetCategory2List, reqGetCategory3List, reqDeleteClassification } from '@/api/product/category'
import type { CategoryListModel, CategoryModel } from '@/api/product/model/categoryModel'
import type Item from '@/layout/components/Sidebar/Item'
const loading = ref(false)

// 一二三级数据
const category1List = ref<CategoryListModel>([])

// 获取一级
const getCategory1List = async () => {
    loading.value = true
    category1List.value = await reqGetCategory1List()
    ElMessage.success('一级分类数据获取成功...')
    category1List.value.forEach(item => {
        // 用于显示展开按钮
        item.hasChildren = true
        // 用于说明当前分类对象的等级  为了row-key实现唯一标识来使用的
        item.level = 1
    })
    loading.value = false
}

// 动态确定当前行的唯一key
const getRowKey = (row: CategoryModel) => {
    return row.level + '-' + row.id
}
onMounted(() => {
    getCategory1List()
})

// 
const load = async (row: CategoryModel, treeNode: unknown, resolve: (data: CategoryModel[]) => void) => {

    if (row.level === 1) {
        const category2List = await reqGetCategory2List(row.id)
        // console.log(category2List);
        ElMessage.success('二级分类数据获取成功...')
        category2List.forEach(item => {
            item.hasChildren = true
            item.level = 2
        });

        resolve(category2List)
    }
    if (row.level === 2) {
        const category3List = await reqGetCategory3List(row.id)
        // console.log(category3List);
        ElMessage.success('三级分类数据获取成功...')
        category3List.forEach(item => {
            item.hasChildren = false
            item.level = 3
        });

        resolve(category3List)
    }


}
</script>


<style>
</style>